<?php defined('SYSPATH') or die('No direct script access.');
                          
class Cart_Controller extends Template_Controller 
{
	public $template = 'layout/cart';
	
	public function __construct()
	{
		parent::__construct();
		
		$this->session = new Session();
		$this->cart = $this->session->get('cart');
		
		$this->db = new Database();

		$this->template->menu = '';
		$this->template->content = '';
		$this->template->leftmenu = $this->db->query('SELECT * FROM product_categories WHERE left_id>1 AND right_id <(SELECT right_id FROM product_categories WHERE id=1) AND layer_id<=2 ORDER BY left_id');
	}
	
	public function index()
	{
		$view = new View('cart/view');
		$view->products = $this->db->query('SELECT * FROM products WHERE id in ('.(isset($this->cart['ids']) ? $this->cart['ids'] : '0').')');
		$view->carts = $this->cart;
		$this->template->content =  $view->render();
	}
	
	public function add($product_id, $quantities)
	{
		if($this->cart)
		{
			if(isset($this->cart['items'][$product_id]['quantities']))
				$this->cart['items'][$product_id]['quantities'] = $this->cart['items'][$product_id]['quantities']+$quantities;
			else
				$this->cart['items'][$product_id]['quantities'] = $quantities;
		}
		else
			$this->cart['items'][$product_id]['quantities'] = $quantities;
			
		$model = new Product_Model($product_id);
		
		$this->cart['items'][$product_id]['price'] = $model->price;
		$this->cart['items'][$product_id]['weight'] = $model->weight;
		$this->cart['items'][$product_id]['stock'] = $model->quantity;
		
		self::update();
		
		echo 'window.location = "'.url::site('cart').'";';
		exit;
	}
	
	protected function update()
	{
		$items_sum = 0;
		$items_total = 0;
		$items_weight = 0;
		$ids = '0';
		
		if(isset($this->cart['items']))
		{
			foreach($this->cart['items'] as $key=>$item)
			{
				$ids .= ','.$key;
				
				if ($item['quantities'] > $item['stock']) continue;
				
				$items_sum++;
				$items_total += $item['price'] * $item['quantities'];
				$items_weight += $item['weight'] * $item['quantities'];
			}
		}
		
		$this->cart['items_sum'] = $items_sum;
		$this->cart['items_total'] = sprintf("%0.2f", $items_total);
		$this->cart['items_weight'] = sprintf("%0.2f", $items_weight);
		$this->cart['ids'] = $ids;
		
		$this->session->set('cart', $this->cart);
	}
		
	public function signin($return_url='cart')
	{
		if(cookie::get('userid'))
		{
			url::redirect(str_replace('_', '/', $return_url), 301);
			exit;
		}
		
		$this->template->content =  new View('cart/signin', array('return_url'=>$return_url));
	}
	
	public function checklogin()
	{
		$db = new Database();
		
		$result = $db->query("SELECT id, username, firstname, lastname FROM customers WHERE username='".$_POST['username']."' AND password='".base64_encode($_POST['password'])."'");

		foreach($result as $item)
		{
			cookie::set('userid', $item->id);
			cookie::set('username', $item->username);
			cookie::set('firstname', $item->firstname);
			cookie::set('lastname', $item->lastname);
		}
	
		url::redirect(str_replace('_', '/', $_POST['return_url']), 301);
		exit;
	}
	
	public function addseries($product_id)
	{
		$result = $this->db->query("select * from products where series=(select series from products where id=".$product_id.")");
		
		if($result)
		{
			foreach($result as $item)
			{
				if(isset($this->cart['items'][$item->id])) continue;
				$this->cart['items'][$item->id]['quantities'] = 1;
				$model = new Product_Model($item->id);
				$this->cart['items'][$item->id]['price'] = $model->price;
				$this->cart['items'][$item->id]['weight'] = $model->weight;
				$this->cart['items'][$item->id]['stock'] = $model->quantity;
			}
		
			self::update();
		}
		
		url::redirect('cart');
	}
	
	public function changequantity()
	{
		if($this->cart['items'])
		{		
			foreach($this->cart['items'] as $key=>$item)
			{
				if($_POST['qid'.$key] == 0)
				{
					unset($this->cart['items'][$key]);
				}
				elseif($_POST['qid'.$key] != $item['quantities'])
				{
					$this->cart['items'][$key]['quantities'] = $_POST['qid'.$key] < 0 ? 1 : $_POST['qid'.$key];
				}
			}
			
			self::update();
		}
		
		url::redirect('cart');
	}
	
	public function quantity($product_id, $quantities)
	{
		if($quantities == 0)
		{
			unset($this->cart['items'][$product_id]);
		}
		else
		{
			$this->cart['items'][$product_id]['quantities'] = $quantities;
		}
		
		self::update();
		url::redirect('cart');
	}
	
	public function delete($product_id)
	{
		unset($this->cart['items'][$product_id]);
		self::update();
		url::redirect('cart');
	}
}